﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YJKCodeBase.WinForm;

namespace FamilyCompare
{
	public partial class FrmFamilyCompare : System.Windows.Forms.Form
	{
		public WindowHandle RevitHandle { get; set; }

		public FrmFamilyCompare(Document doc, UIApplication uiapp)
		{
			this.document = doc;
			this.uiapplication = uiapp;
			this.InitializeComponent();
		}

		public FrmFamilyCompare(Document doc, UIApplication uiapp, WindowHandle revitHandle)
		{
			this.document = doc;
			this.uiapplication = uiapp;
			this.RevitHandle = revitHandle;
			this.InitializeComponent();
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private List<Document> GetRevitLinkedDocument(Document m_doc)
		{
			List<Document> list = new List<Document>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(m_doc);
			ElementClassFilter elementClassFilter = new ElementClassFilter(typeof(RevitLinkInstance));
			ICollection<Element> collection = filteredElementCollector.WherePasses(elementClassFilter).ToElements();
			if (collection.Count < 1)
			{
				return null;
			}
			foreach (Element element in collection)
			{
				try
				{
					RevitLinkInstance revitLinkInstance = element as RevitLinkInstance;
					list.Add(revitLinkInstance.GetLinkDocument());
				}
				catch
				{
					return null;
				}
			}
			return list;
		}

		private void btnStartCompare_Click(object sender, EventArgs e)
		{
			if (this.txtFile1.Text == "" || this.txtFile2.Text == "")
			{
				YJKMessageBox.Show("请选择两个需要比对的文件！");
				return;
			}
			if (this.txtFile1.Text == this.txtFile2.Text)
			{
				YJKMessageBox.Show("两个需要比对的文件不能为相同的文件，请重新选择！");
				return;
			}
			DocumentResultPacker documentResultPacker = null;
			DocumentResultPacker documentResultPacker2 = null;
			try
			{
				if (this.chklsIsCurrentProject.Checked)
				{
					Document doc = this.uiapplication.ActiveUIDocument.Document;
					documentResultPacker = this.CreateDocumentResultPacker(doc);
				}
				else
				{
					Document document = this.uiapplication.Application.OpenDocumentFile(this.txtFile1.Text);
					documentResultPacker = this.CreateDocumentResultPacker(document);
					document.Close(false);
				}
			}
			catch (Exception)
			{
				YJKMessageBox.Show("文件1被占用或者链接文件失效，请关闭或者勾选当前项目后继续进行该操作！");
				return;
			}
			try
			{
				Document document2 = this.uiapplication.Application.OpenDocumentFile(this.txtFile2.Text);
				documentResultPacker2 = this.CreateDocumentResultPacker(document2);
				document2.Close(false);
			}
			catch
			{
				YJKMessageBox.Show("文件2被占用或文件2中链接文件失效，请核对！");
				return;
			}
			if (documentResultPacker.LstLinkDocumentResults.Count == documentResultPacker2.LstLinkDocumentResults.Count)
			{
				FrmCompareResult frmCompareResult = new FrmCompareResult(documentResultPacker, documentResultPacker2);
				frmCompareResult.Show(this.RevitHandle);
				return;
			}
			YJKMessageBox.Show("选择的两个文件链接实例个数不同无法进行比较");
		}

		private DocumentResultPacker CreateDocumentResultPacker(Document doc)
		{
			DocumentResultPacker documentResultPacker = new DocumentResultPacker(false, null, doc);
			documentResultPacker.MakeResultList();
			List<Document> revitLinkedDocument = this.GetRevitLinkedDocument(doc);
			if (revitLinkedDocument != null && revitLinkedDocument.Count > 0)
			{
				for (int i = 0; i < revitLinkedDocument.Count; i++)
				{
					DocumentResultPacker documentResultPacker2 = new DocumentResultPacker(true, documentResultPacker, revitLinkedDocument[i]);
					documentResultPacker2.MakeResultList();
					documentResultPacker.LstLinkDocumentResults.Add(documentResultPacker2);
				}
			}
			return documentResultPacker;
		}

		private void chklsIsCurrentProject_CheckedChanged(object sender, EventArgs e)
		{
			if (this.chklsIsCurrentProject.Checked)
			{
				try
				{
					this.txtFile1.Text = this.uiapplication.ActiveUIDocument.Document.PathName;
				}
				catch (Exception)
				{
					this.txtFile1.Text = "";
				}
				this.btnLoadFile1.Enabled = false;
				return;
			}
			this.txtFile1.Text = null;
			this.btnLoadFile1.Enabled = true;
		}

		private void FrmFamilyCompare_Load(object sender, EventArgs e)
		{
			//base.Icon = Resource.YArchitechIcon;
			this.ReadData();
			if (this.document == null || this.document.PathName == null || this.document.PathName.ToString().Trim() == "")
			{
				this.chklsIsCurrentProject.Enabled = false;
				return;
			}
			this.chklsIsCurrentProject.Enabled = true;
		}

		protected override bool ProcessKeyEventArgs(ref Message m)
		{
			int num = 256;
			int num2 = 27;
			if (m.Msg == num && m.WParam.ToInt32() == num2)
			{
				base.Close();
			}
			return base.ProcessKeyEventArgs(ref m);
		}

		private bool ReadData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "FamilyCompareLayout.dat";
			try
			{
				FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
				StreamReader streamReader = new StreamReader(fileStream);
				bool flag = false;
				if (streamReader.ReadLine() == "True")
				{
					this.chklsIsCurrentProject.Enabled = true;
					if (streamReader.ReadLine() == "True")
					{
						flag = true;
						this.chklsIsCurrentProject.Checked = true;
						this.txtFile1.Text = this.uiapplication.ActiveUIDocument.Document.PathName;
					}
					else
					{
						this.chklsIsCurrentProject.Checked = false;
					}
				}
				else
				{
					this.chklsIsCurrentProject.Enabled = false;
					streamReader.ReadLine();
				}
				this.ofdLoadFile1.InitialDirectory = streamReader.ReadLine();
				this.ofdLoadFile2.InitialDirectory = streamReader.ReadLine();
				if (!flag)
				{
					this.txtFile1.Text = streamReader.ReadLine();
					this.txtFile2.Text = streamReader.ReadLine();
				}
				else
				{
					streamReader.ReadLine();
					this.txtFile2.Text = streamReader.ReadLine();
				}
				streamReader.Close();
				fileStream.Close();
			}
			catch
			{
				this.chklsIsCurrentProject.Enabled = true;
				this.chklsIsCurrentProject.Checked = true;
				this.txtFile1.Text = "e:\\";
				this.txtFile1.Text = "e:\\";
			}
			return true;
		}

		private bool SaveData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "FamilyCompareLayout.dat";
			FileStream fileStream = new FileStream(path, FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			if (this.txtFile1.Text == "" || this.txtFile2.Text == "")
			{
				return false;
			}
			try
			{
				streamWriter.WriteLine(this.chklsIsCurrentProject.Enabled.ToString());
				streamWriter.WriteLine(this.chklsIsCurrentProject.Checked.ToString());
				try
				{
					streamWriter.WriteLine(this.txtFile1.Text.Substring(0, this.txtFile1.Text.LastIndexOf("\\")));
				}
				catch
				{
					streamWriter.WriteLine(this.txtFile1.Text.Substring(0, this.txtFile1.Text.IndexOf("\\")));
				}
				try
				{
					streamWriter.WriteLine(this.txtFile2.Text.Substring(0, this.txtFile2.Text.LastIndexOf("\\")));
				}
				catch
				{
					streamWriter.WriteLine(this.txtFile2.Text.Substring(0, this.txtFile2.Text.IndexOf("\\")));
				}
				streamWriter.WriteLine(this.txtFile1.Text);
				streamWriter.WriteLine(this.txtFile2.Text);
				streamWriter.Flush();
				streamWriter.Close();
				fileStream.Close();
			}
			catch (Exception)
			{
				fileStream = new FileStream(path, FileMode.Create);
				fileStream.Close();
			}
			return true;
		}

		private void btnLoadFile1_Click(object sender, EventArgs e)
		{
			this.ofdLoadFile1.Filter = "rvt|*.rvt";
			this.ofdLoadFile1.RestoreDirectory = true;
			if (this.ofdLoadFile1.ShowDialog() == DialogResult.OK)
			{
				this.txtFile1.Text = this.ofdLoadFile1.FileName;
				this.sFilePath1 = this.ofdLoadFile1.FileName.Substring(0, this.ofdLoadFile1.FileName.LastIndexOf("\\"));
			}
		}

		private void btnLoadFile2_Click(object sender, EventArgs e)
		{
			this.ofdLoadFile2.Filter = "rvt|*.rvt";
			this.ofdLoadFile2.RestoreDirectory = true;
			if (this.ofdLoadFile2.ShowDialog() == DialogResult.OK)
			{
				this.txtFile2.Text = this.ofdLoadFile2.FileName;
				this.sFilePath2 = this.ofdLoadFile2.FileName.Substring(0, this.ofdLoadFile2.FileName.LastIndexOf("\\"));
			}
		}

		private void FrmFamilyCompare_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == '\u001b')
			{
				base.Close();
			}
		}

		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		private void SendESC()
		{
			byte bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			FrmFamilyCompare.keybd_event(bVk, 0, dwFlags, 0);
			FrmFamilyCompare.keybd_event(bVk, 0, dwFlags2, 0);
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private void FrmFamilyCompare_FormClosed(object sender, FormClosedEventArgs e)
		{
			int wMsg = 7;
			FrmFamilyCompare.SendMessage(FamilyCompareCommand._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			this.SaveData();
			this.SendESC();
		}

		private Document document;

		private UIApplication uiapplication;

		private string sFilePath1 = "";

		private string sFilePath2 = "";
	}
}
